package com.bootdo.coach.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.coach.domain.TabDevice;
import com.bootdo.coach.domain.TabDeviceType;
import com.bootdo.coach.domain.TabUser;
import com.bootdo.coach.service.TabDeviceService;
import com.bootdo.coach.service.TabDeviceTypeService;
import com.bootdo.coach.service.TabUserService;
import com.bootdo.coach.vo.TabDeviceVo;
import com.bootdo.coach.vo.TabDeviceVo2;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

import io.swagger.annotations.ApiOperation;

@RequestMapping("/device/device")
@Controller
public class DeviceController extends BaseController{
	private String prefix = "msg/device";

	@Autowired
	private TabDeviceService deviceService;
	
	@Autowired
	private TabUserService userService;

	@Autowired
	private TabDeviceTypeService deviceTypeService;
	
	@Value("${bootdo.httpUrl}")
	private String httpUrl;
	
	@Value("${bootdo.uploadPath}")
	private String uploadPath;
	
	@RequiresPermissions("device:device:list")
	@GetMapping("list")
	String list(Model model) {
		return prefix + "/list";
	}
	
	@ApiOperation(value="获取设备列表", notes="")
	@ResponseBody
	@GetMapping("/dataList")
	@RequiresPermissions("device:device:list")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		params.put("deviceTypeId", getUser().getDeviceTypeId());
        Query query = new Query( params );
		List<TabDeviceVo> list = deviceService.list(query);
		int total = deviceService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}
	
	private List<TabDeviceType> getAllDeviceType() {
		List<TabDeviceType> deviceTypes = deviceTypeService.list(new HashMap<String, Object>());
		if (deviceTypes == null) {
			deviceTypes = new ArrayList<TabDeviceType>();
		}
		TabDeviceType one = new TabDeviceType();
		one.setId(0l);
		one.setDeviceTypeName("请选择");
		deviceTypes.add(0, one);
		return deviceTypes;
	}

	@RequiresPermissions("device:device:addDevice")
	@Log("添加设备")
	@GetMapping("/addDevice")
	String addDevice(Model model) {
		model.addAttribute("deviceTypes", getAllDeviceType());
		return prefix + "/add";
	}

	@RequiresPermissions("device:device:updateDevice")
	@Log("编辑设备")
	@GetMapping("/updateDevice/{id}")
	String updateDevice(Model model, @PathVariable("id") Long id) {
		model.addAttribute("deviceTypes", getAllDeviceType());
		TabDevice device = deviceService.selectByPrimaryKey(id);
		model.addAttribute("device", device);
		return prefix+"/edit";
	}

	@RequiresPermissions("device:device:addDevice")
	@Log("保存设备")
	@PostMapping("/saveDevice")
	@ResponseBody
	R saveDevice(TabDevice record) {
		if (record.getDeviceTypeId().longValue() == 0) {
			return R.error("请选择产品");
		}
		record.setCreateTime(new Date());
		record.setExpireTime(new Date());
		record.setDeviceContent("");
		record.setOnline(0);
		if (deviceService.insertSelective(record) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/exportExcl")
	@ResponseBody
	R exportExcl(HttpServletResponse response) {
		// 查询列表数据
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("deviceTypeId", getUser().getDeviceTypeId());
		List<TabDeviceVo> list = deviceService.list(params);
		if (list == null || list.isEmpty()) {
			return R.error("没有数据可以导出");
		}
		List<TabDeviceVo2> dataset = new ArrayList<TabDeviceVo2>();
		for (TabDeviceVo tabDeviceVo : list) {
			TabDeviceVo2 deviceVo2 = new TabDeviceVo2();
			deviceVo2.setDeviceTypeName(tabDeviceVo.getDeviceTypeName());
			deviceVo2.setDeviceName(tabDeviceVo.getDeviceName());
			deviceVo2.setSerialNumber(tabDeviceVo.getSerialNumber());
	        deviceVo2.setTotalOnlineMinute(String.valueOf(tabDeviceVo.getTotalOnlineMinute()));
	        dataset.add(deviceVo2);
		}
		
		// 测试学生
        ExportExcel<TabDeviceVo2> ex = new ExportExcel<TabDeviceVo2>();
        String[] headers = { "设备名称", "产品类型", "设备序号", "累计在线时间（分钟）" };
        try
        {
        	String fileName = DateUtils.getNowLongTime() + ".xlsx";
            OutputStream out = new FileOutputStream(uploadPath + fileName);
            ex.exportExcel(headers, dataset, out);
            out.close();
    		return R.ok(httpUrl + fileName);
        }
        catch (Exception e)
        {
			return R.error("导出失败");
        }
	}

	@RequiresPermissions("device:device:updateDevice")
	@Log("更新设备")
	@PostMapping("/update")
	@ResponseBody
	R update(TabDevice record) {
		if (record.getDeviceTypeId().longValue() == 0) {
			return R.error("请选择产品");
		}
		List<TabDevice> list = deviceService.selectByDeviceName(record.getDeviceName());
		if (list != null) {
			for (TabDevice tabDevice : list) {
				if (record.getId().longValue() != tabDevice.getId().longValue()) {
					return R.error("设备名称已经存在");
				}
			}
		}
		list = deviceService.selectBySerialNumber(record.getSerialNumber());
		if (list != null) {
			for (TabDevice tabDevice : list) {
				if (record.getId().longValue() != tabDevice.getId().longValue()) {
					return R.error("设备序号已经存在");
				}
			}
		}
		
		if (deviceService.updateByPrimaryKeySelective(record) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("device:device:deleteDevice")
	@Log("删除设备")
	@PostMapping("/deleteDevice")
	@ResponseBody
	R deleteDevice(Long id) {
		//判断此设备是否有用户在占用
//		TabUser user = userService.findByDeviceId(id);
//		if (user != null) {
//			return R.error("用户(" + user.getAccount()+")正在使用，请先更换他的设备");
//		}
		
		if (deviceService.deleteByPrimaryKey(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exitDeviceName")
	@ResponseBody
	boolean exitDeviceName(@RequestParam Map<String, Object> params) {
		return !deviceService.exitDeviceName(params);
	}
	
	@PostMapping("/exitSerialNumber")
	@ResponseBody
	boolean exitSerialNumber(@RequestParam Map<String, Object> params) {
		return !deviceService.exitSerialNumber(params);
	}
}
